package db

import (
	"GinHelloWorld/model"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"log"
	"time"
)

var DB *gorm.DB

func init() {
	driverName := "mysql"
	host := "127.0.0.1"
	port := "3306"
	database := "test1"
	username := "root"
	password := "123456"
	charset := "utf8"

	args := fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset)

	db, err := gorm.Open(driverName, args)
	if err != nil {
		log.Fatal(err)
		//panic(err)
	}
	db.SingularTable(true) //方法全局禁用表名复数，此时表名默认为结构体首字母小写形式
	//迁移
	db.AutoMigrate(&model.User{})
	// 设置连接池
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)
	db.DB().SetConnMaxLifetime(time.Hour)

	DB = db
}

func GetDB() *gorm.DB {
	return DB
}
